import React, { useEffect } from 'react';
import { Button, DatePicker, message, Radio, Select, Space, Spin } from 'antd';
import moment from 'moment';
import { TRDefault } from '@/components/index.js';
import { UploadOutlined } from '#/utils/antdIcons.js';
import { TjArrow, TjChart, TjTable, useTRState } from '@/pages/ETrade/components';
import { getChartOption, getTableColumns } from './helper';
import { exportData, exportMonthData, fetchData, getMarketList } from './services';
import { useThemeChange } from '@/hooks';
import styles from './index.less';
import MonthSettlement from './MonthlSettlement/index';
import { HttpCode } from '#/utils/contacts';

const getDateRange = (mode) => {
  if (mode === 'month') {
    return [moment().month(0).startOf('month'), moment().endOf('month')];
  }
  return [moment().startOf('month'), moment()];
};

const { RangePicker } = DatePicker;

export default () => {
  const [state, setState] = useTRState({
    dates: getDateRange('date'),
    loading: false,
    result: null,
    openLeft: false,
    openRight: false,
    exporting: false,
    powerData: {},
    priceData: {},
    marketList: [],
    selectValue: 'PHBSX',
    mode: 'date', //'date' | 'month'（默认选择当前年份所有月）
    activeMonthFetch: false, // 触发月份维度查询
    monthSettlementParams: {
      marketId: 'PHBSX',
      beginDate: getDateRange('month')[0].format('YYYYMM'),
      endDate: getDateRange('month')[1].format('YYYYMM'),
    },
  });

  const { theme } = useThemeChange();

  useEffect(() => {
    init();
  }, []);

  useEffect(() => {
    const powerData = getChartOption(state.result?.powerData, 'powerData');
    const priceData = getChartOption(state.result?.priceData, 'priceData');
    setState({
      powerData,
      priceData,
    });
  }, [state.result, theme]);

  const init = async () => {
    setState({
      loading: true,
    });
    const res = await getMarketList();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setState({
        marketList: res?.data?.map((i) => ({ ...i, label: i.description })) || [],
      });
    } else {
      setState({
        result: res.message,
      });
      message.error(res.message);
    }
    setState({
      loading: false,
    });
    _onReset();
  };

  const _onFinish = async (data) => {
    const { selectValue } = state;
    if (data.mode === 'month') {
      const params = {
        marketId: selectValue,
        beginDate: data.dates[0].format('YYYYMM'),
        endDate: data.dates[1].format('YYYYMM'),
      };
      setState({
        dates: data.dates,
        mode: data.mode,
        activeMonthFetch: true,
        monthSettlementParams: params,
        selectValue: data.marketId,
        formValue: {
          dates: data.dates,
          mode: data.mode,
        },
      });
    } else {
      setState({
        formValue: {
          dates: data.dates,
          mode: data.mode,
        },
        dates: data.dates,
        mode: data.mode,
        selectValue: data.marketId,
        loading: true,
      });
      const res = await fetchData({
        beginDate: data.dates[0].format('YYYY-MM-DD'),
        endDate: data.dates[1].format('YYYY-MM-DD'),
      });
      const result = res?.data || null;
      setState({
        result,
        loading: false,
      });
    }
  };

  const _onReset = () => {
    _onFinish({
      dates: getDateRange('date'),
      mode: 'date',
      marketId: 'PHBSX',
    });
  };

  const _onExport = async () => {
    if (state.exporting) return;
    setState({ exporting: true });
    if (state.mode === 'month') {
      await exportMonthData(state.monthSettlementParams);
      // will 月维度导出
      setState({ exporting: false });
      return;
    }
    const { dates } = state;
    await exportData({
      beginDate: dates[0].format('YYYY-MM-DD'),
      endDate: dates[1].format('YYYY-MM-DD'),
    });
    setState({ exporting: false });
  };

  const changeMode = (e) => {
    const mode = e.target.value;
    const dates = getDateRange(mode);
    _onFinish({
      dates,
      mode,
      marketId: selectValue,
    });
  };

  /** render */
  const _renderMain = () => {
    if (state.loading) return null;
    if (!state.result) return <TRDefault type="empty" />;
    const { dates } = state;
    let tableTitle = `${dates[0].format('YYYYMMDD')}-${dates[1].format('YYYYMMDD')}`;
    tableTitle += ' 市场机组结算统计';
    const tableData = state.result?.statisticDataList || [];
    const tableColumns = getTableColumns(tableData);
    return (
      <>
        <div
          className={styles.box}
          style={{ width: state.openLeft ? '100%' : state.openRight ? 0 : '60%' }}
        >
          <div className={styles.boxInner}>
            <TjArrow
              value={state.openLeft}
              position="right"
              onChange={(v) => setState({ openLeft: v })}
            />
            <div className={styles.title}>
              <span className={styles.title_name}>发电侧分日电量组成</span>
              <span className={styles.title_unit}>单位：MWh</span>
            </div>
            <div className={styles.chart}>
              {/* <TjChart group="1" option={getChartOption(state.result?.powerData, 'powerData')} /> */}
              <TjChart group="1" option={state.powerData} />
            </div>
            <div className={styles.title}>
              <span className={styles.title_name}>发电侧分日结算价格对比</span>
              <span className={styles.title_unit}>单位：元/MWh</span>
            </div>
            <div className={styles.chart}>
              {/* <TjChart group="1" option={getChartOption(state.result?.priceData, 'priceData')} /> */}
              <TjChart group="1" option={state.priceData} />
            </div>
          </div>
        </div>
        <div
          className={styles.box}
          style={{ width: state.openRight ? '100%' : state.openLeft ? 0 : '40%' }}
        >
          <TjArrow
            value={state.openRight}
            position="left"
            onChange={(v) => setState({ openRight: v })}
          />
          <div className={styles.boxInner}>
            <div className={styles.title}>
              <span className={styles.title_name}>{tableTitle}</span>
            </div>
            <div className={styles.table}>
              <TjTable
                dataSource={tableData}
                columns={tableColumns}
                style={{
                  '--row-height': '20px',
                  '--cell-padding': '0px 8px',
                }}
              />
            </div>
          </div>
        </div>
      </>
    );
  };
  const { loading, dates, exporting, marketList, selectValue, mode, monthSettlementParams } = state;

  return (
    <Spin spinning={loading}>
      <div className={styles.container}>
        <div className={styles.head}>
          <Space size={16} wrap>
            <Select
              style={{ width: 200 }}
              value={selectValue}
              // 切换为日的时候只能选择山西交易中
              options={mode === 'date' ? marketList.filter((i) => i.value === 'PHBSX') : marketList}
              onChange={(selectValue) => setState({ selectValue })}
            />
            {/* <DatePicker.RangePicker
              style={{ width: 256 }}
              value={dates}
              separator="-"
              format={'YYYYMMDD'}
              disabledDate={(v) => v > moment()}
              allowClear={false}
              onChange={(dates) => setState({ dates })}
            /> */}
            <div>
              <Radio.Group buttonStyle="solid" value={mode} onChange={changeMode}>
                <Radio.Button value="month">月</Radio.Button>
                <Radio.Button value="date">日</Radio.Button>
              </Radio.Group>
              <RangePicker
                picker={mode}
                style={{ width: 256 }}
                value={dates}
                separator="-"
                format={mode === 'date' ? 'YYYYMMDD' : 'YYYYMM'}
                disabledDate={mode === 'date' ? (v) => v > moment() : null}
                allowClear={false}
                onChange={(dates) => setState({ dates })}
              />
            </div>
            <Space size={16}>
              <Button
                style={{ width: 98, height: 32 }}
                type="primary"
                onClick={() =>
                  _onFinish({
                    dates,
                    mode,
                    marketId: selectValue,
                  })
                }
              >
                查询
              </Button>
              <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
                重置
              </Button>
            </Space>
          </Space>
          <Space size={16} wrap>
            <Button
              style={{ padding: 0 }}
              type="link"
              icon={<UploadOutlined />}
              disabled={exporting}
              onClick={_onExport}
            >
              导出
            </Button>
          </Space>
        </div>
        <div className={styles.main}>
          {mode === 'date' ? (
            _renderMain()
          ) : (
            <MonthSettlement
              marketList={marketList}
              setState={setState}
              queryValue={monthSettlementParams}
              activeMonthFetch={state.activeMonthFetch}
            />
          )}
        </div>
      </div>
    </Spin>
  );
};
